package controller;

import common.Result;
import entity.ResearchProjects;
import service.ResearchProjectsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;

@RestController
@RequestMapping("/api/researchprojects")
public class ResearchProjectsController {

    @Autowired
    private ResearchProjectsService researchProjectsService;

    @GetMapping("/{id}")
    public Result getById(@PathVariable Integer id) {
        try {
            ResearchProjects project = researchProjectsService.getById(id);
            if (project != null) {
                return Result.success(project);
            } else {
                return Result.error("科研项目不存在", 404);
            }
        } catch (Exception e) {
            return Result.error("获取科研项目失败: " + e.getMessage(), 500);
        }
    }

    @GetMapping("/all")
    public Result getAll() {
        try {
            List<ResearchProjects> projects = researchProjectsService.getAll();
            return Result.success(projects);
        } catch (Exception e) {
            return Result.error("获取所有科研项目失败: " + e.getMessage(), 500);
        }
    }

    @GetMapping("/student/{studentId}")
    public Result getByStudentId(@PathVariable Integer studentId) {
        try {
            List<ResearchProjects> projects = researchProjectsService.getByStudentId(studentId);
            return Result.success(projects);
        } catch (Exception e) {
            return Result.error("获取学生科研项目失败: " + e.getMessage(), 500);
        }
    }

    @PostMapping
    public Result create(@RequestBody ResearchProjects obj) {
        try {
            int result = researchProjectsService.create(obj);
            if (result > 0) {
                return Result.success("添加科研项目成功", result);
            } else {
                return Result.error("添加科研项目失败", 400);
            }
        } catch (Exception e) {
            return Result.error("添加科研项目失败: " + e.getMessage(), 500);
        }
    }

    @PutMapping
    public Result update(@RequestBody ResearchProjects obj) {
        try {
            int result = researchProjectsService.update(obj);
            if (result > 0) {
                return Result.success("更新科研项目成功", result);
            } else {
                return Result.error("更新科研项目失败", 400);
            }
        } catch (Exception e) {
            return Result.error("更新科研项目失败: " + e.getMessage(), 500);
        }
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        try {
            int result = researchProjectsService.delete(id);
            if (result > 0) {
                return Result.success("删除科研项目成功", result);
            } else {
                return Result.error("删除科研项目失败", 400);
            }
        } catch (Exception e) {
            return Result.error("删除科研项目失败: " + e.getMessage(), 500);
        }
    }
}